package com.tul.exercise.base.thread.base;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * Callable接口的使用
 */
public class CallabelDemo {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        ArrayList<Future<String>> results = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            results.add(service.submit(new TaskWithResult(i)));
        }


        for (Future<String> future : results) {
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {
                System.out.println(e);
            } catch (ExecutionException e) {
                System.out.println(e);
            } finally {
                service.shutdown();
            }
        }


    }

}


/**
 * 可以返回结果的任务
 */
class TaskWithResult implements Callable {
    private int id;

    public TaskWithResult(int id) {
        this.id = id;
    }

    @Override
    public Object call() throws Exception {
        return "result of TaskWithResult " + id;
    }
}
